[Java] Send cookie with http request problem
Posted
by nkr1pt
on Stack Overflow
See other posts from Stack Overflow
or by nkr1pt
Published on 2010-03-27T10:41:47Z
Indexed on
2010/03/27
10:43 UTC
Read the original article
Hit count: 314
I'm trying to get a certain cookie in a java client by creating a series of Http requests. It looks like I'm getting a valid cookie from the server but when I'm sending out a request to the fnal url with the seemingly valid cookie I should get some lines of xml in the response but the response is blank because the cookie isw rong or is invalidated because a session has closed or an other problem which I can't figure out. The cookie handed out by the server expires at the end of the session.
It seems to me the cookie is valid because when I do the same calls in firefox, a similar cookie with the same name and starting with the 3 first same letters and of the same length is stored in firefox, also expiring at the end of the session. If I then make a request to the final url with only this particular cookie stored in firefox (removed all other cookies), the xml is nicely rendered on the page.
Any ideas about what I am doing wrong in this piece of code? One other thing, when I use the value from the very similar cookie generated and strored in firefox in this piece of code, the last request does give xml feedback in the http response!
// Validate
url = new URL(URL_VALIDATE);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
if (conn.getHeaderField(i).startsWith("JSESSIONID")) {
cookie = conn.getHeaderField(i).substring(0, conn.getHeaderField(i).indexOf(";")).trim();
}
}
}
// Get the XML
url = new URL(URL_XML_TOTALS);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
reader.close();
//Output the response
System.out.println(answer.toString())
© Stack Overflow or respective owner